import 'package:flutter/material.dart';
// 若要修复该问题，需要在 pubspec.yaml 中添加 shared_preferences 依赖
// 以下是添加依赖后的导入语句，确保已在 pubspec.yaml 中添加依赖
import 'package:shared_preferences/shared_preferences.dart';
// 为了使用 Timer 类，需要引入 dart:async 库
import 'dart:async';

class SalaryCalculatorPage extends StatefulWidget {
  const SalaryCalculatorPage({super.key});

  @override
  State<SalaryCalculatorPage> createState() => _SalaryCalculatorPageState();
}

class _SalaryCalculatorPageState extends State<SalaryCalculatorPage> {
  final _salaryController = TextEditingController();
  double _monthlySalary = 0;
  double _perSecond = 0;
  double _totalEarned = 0;
  DateTime? _startTime;

  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _loadSavedSalary();
  }

  Future<void> _loadSavedSalary() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _monthlySalary = prefs.getDouble('monthlySalary') ?? 0;
      _salaryController.text = _monthlySalary.toStringAsFixed(2);
    });
  }

  void _startCalculation() {
    final monthly = double.tryParse(_salaryController.text) ?? 0;
    if (monthly <= 0) return;

    setState(() {
      _monthlySalary = monthly;
      _startTime = DateTime.now();
      _perSecond = _monthlySalary / (30 * 24 * 3600);
      _totalEarned = 0;
    });

    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      final now = DateTime.now();
      final diff = now.difference(_startTime!);
      setState(() {
        _totalEarned = _perSecond * diff.inSeconds;
      });
    });

    SharedPreferences.getInstance().then((prefs) {
      prefs.setDouble('monthlySalary', monthly);
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    _salaryController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('薪资计算器')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _salaryController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '输入月薪（元）',
                border: OutlineInputBorder(),
                suffixText: '元',
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _startCalculation,
              child: const Text('开始计算'),
            ),
            const SizedBox(height: 30),
            Text(
              '每秒收入：¥${_perSecond.toStringAsFixed(4)}',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 15),
            Text(
              '今日累计：¥${_totalEarned.toStringAsFixed(2)}',
              style: Theme.of(
                context,
              ).textTheme.headlineSmall?.copyWith(color: Colors.green),
            ),
          ],
        ),
      ),
    );
  }
}
